package quick.start.core.connect;


import android.content.Context;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;

import quick.start.core.ApplicationBase;
import quick.start.core.util.CoreLog;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * 网络状态管理类
 * @author 吴昊颖
 * @version 1.0.0
 * @date 2013-6-23
 *
 */
public class NetStateManager {
	private static List<OnNetStateChangedListener> onNetStateChangedListeners;
	public static NetState CURRENT_NET_STATE = NetState.NoWay;
	public static String MOBILE_PROXY = null;
	private static NetStateReceiver receiver = null;
	private final static String NET_DETECT_URL = "http://ip.qq.com/cgi-bin/myip";
	private final static String TAG = "NetStateManager";
	
	public enum NetState{
		Mobile,
		Wifi,
		NoWay
	}
	
	public static void init(Context context){
		CURRENT_NET_STATE = NetState.NoWay;
		getCurrentNetState(context);
	}
	
	public static void onExit(Context context){
		if(null != receiver){
			context.unregisterReceiver(receiver);
			CURRENT_NET_STATE = NetState.NoWay;
			receiver = null;
			onNetStateChangedListeners = null;
		}
	}
	
	public static boolean onNet(){
		return onNet(true);
	}
	
	public static boolean onNet(boolean retrive){
		if(retrive){
			getCurrentNetState(ApplicationBase.getApplication());
		}
		return CURRENT_NET_STATE != NetState.NoWay;
	}
	
	public static boolean isWifi(){
		return CURRENT_NET_STATE != NetState.Wifi;
	}
	
	/**
	 * 检查当前是否为高速网络
	 * @param context 应用上下文
	 * @param checkMobile 是否检查高速移动网络
	 * @return
	 */
	public static boolean isFastConnected(Context context, boolean checkMobile){
		ConnectivityManager connectivityManager = 
				(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		
		if(networkInfo != null){
			int netType = networkInfo.getType();
			int subType = networkInfo.getSubtype();
			return isConnetionFast(netType, subType, checkMobile);
		}else{
			return false;
		}
	}
	
	public static boolean hasNet(){
		return CURRENT_NET_STATE != NetState.NoWay;
	}
	
	protected static NetState getCurrentNetState(Context context){
		ConnectivityManager connectivityManager = 
				(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		
		if(networkInfo != null){
			int netType = networkInfo.getType();
			int subType = networkInfo.getSubtype();
			if(isConnetionFast(netType, subType, false)){
				NetStateManager.CURRENT_NET_STATE = NetState.Wifi;
			}
			else{
				NetStateManager.CURRENT_NET_STATE = NetState.Mobile;
			}
		}else{
			NetStateManager.CURRENT_NET_STATE = NetState.NoWay;
		}
		CoreLog.i(TAG, NetStateManager.CURRENT_NET_STATE);
		notifyNetStateChanged();
		return NetStateManager.CURRENT_NET_STATE;
	}
	
	private static void notifyNetStateChanged(){
		if(null != onNetStateChangedListeners && onNetStateChangedListeners.size() != 0){
			for (OnNetStateChangedListener listener : onNetStateChangedListeners) {
				listener.onNetStateChanged(CURRENT_NET_STATE);
			}
		}
	}
	
	public static void registerNetStateChangedListener(OnNetStateChangedListener listener){
		if(null != onNetStateChangedListeners){
			onNetStateChangedListeners.add(listener);
		}
	}
	
	public static void unregisterNetStateChangedListener(OnNetStateChangedListener listener){
		if(null != onNetStateChangedListeners){
			onNetStateChangedListeners.remove(listener);
		}
	}
	
    /**
     * 判断是否联网
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] infos = connectivity.getAllNetworkInfo();
            if (infos != null) {
                for (NetworkInfo info : infos) {
                    if (NetworkInfo.State.CONNECTED == info.getState()) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    
    public static String getIp(){
        URL infoUrl = null;
        InputStream inStream = null;
        try {
            infoUrl = new URL(NET_DETECT_URL);
            URLConnection connection = infoUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection)connection;
            int responseCode = httpConnection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK)
            {
                inStream = httpConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"utf-8"));
                StringBuilder strber = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null)
                    strber.append(line + "\n");
                inStream.close();
                return strber.toString();
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }
	
	/**
	 * 检查是否处于高速网络环境
	 * @param type 网络类型
	 * @param subType 子网络类型
	 * @param checkMobileNet 当网络类型为移动网络时是否检查
	 * @return true=高速网络 false=低速网络
	 */
	protected static boolean isConnetionFast(int type, int subType,
			boolean checkMobileNet) {
		if (type == ConnectivityManager.TYPE_WIFI) {
			CoreLog.d(TAG, "Connected via Wifi");
			return true;
		} else if (type == ConnectivityManager.TYPE_MOBILE && checkMobileNet) {
			switch (subType) {
			case TelephonyManager.NETWORK_TYPE_1xRTT:
				return false; // ~ 50-100 kbps
			case TelephonyManager.NETWORK_TYPE_CDMA:
				return false; // ~ 14-64 kbps
			case TelephonyManager.NETWORK_TYPE_EDGE:
				return false; // ~ 50-100 kbps
			case TelephonyManager.NETWORK_TYPE_EVDO_0:
				return true; // ~ 400-1000 kbps
			case TelephonyManager.NETWORK_TYPE_EVDO_A:
				return true; // ~ 600-1400 kbps
			case TelephonyManager.NETWORK_TYPE_GPRS:
				return false; // ~ 100 kbps
			case TelephonyManager.NETWORK_TYPE_HSDPA:
				return true; // ~ 2-14 Mbps
			case TelephonyManager.NETWORK_TYPE_HSPA:
				return true; // ~ 700-1700 kbps
			case TelephonyManager.NETWORK_TYPE_HSUPA:
				return true; // ~ 1-23 Mbps
			case TelephonyManager.NETWORK_TYPE_HSPAP:
				return true; // ~ 1-23 Mbps
			case TelephonyManager.NETWORK_TYPE_UMTS:
				return true; // ~ 400-7000 kbps
				// Unknown
			case TelephonyManager.NETWORK_TYPE_UNKNOWN:
				return false;
			default:
				return false;
			}
		} else {
			return false;
		}
	}
	
    @Deprecated
    static void initMobileProxy(Context context) {
        //先清空，避免WAP切换到NET时的错误
        MOBILE_PROXY = null;
        Uri uri = Uri.parse("content://telephony/carriers/preferapn");
        Cursor mCursor = null;
        if (null != context) {
            mCursor = context.getContentResolver().query(uri, null, null, null, null);
        }
        if (mCursor != null && mCursor.moveToFirst()) {
            // 游标移至第一条记录，当然也只有一条
            String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
            if (proxyStr != null && proxyStr.trim().length() > 0) {
                MOBILE_PROXY = proxyStr;
            }
            mCursor.close();
        }
    }


    /**
     * 获取 当前apn并返回httphost对象
     *
     * @return
     */
    @Deprecated
    public static HttpHost getAPN() {
        HttpHost proxy = null;

        if (StringUtils.isNotBlank(MOBILE_PROXY)) {
            proxy = new HttpHost(MOBILE_PROXY, 80);
        }
        return proxy;
    }
    
    //初始化连接类型，应用启动时调用
    @Deprecated
    public static void initCurrConnectionType(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        if (wifiManager.isWifiEnabled()) {
            CURRENT_NET_STATE = NetState.Wifi;
        }
        if (!wifiManager.isWifiEnabled() || -1 == info.getNetworkId()) {
            NetStateManager.CURRENT_NET_STATE = NetStateManager.NetState.Mobile;
            initMobileProxy(context);
        }
        if (isNetworkAvailable(context) == false) {
        	CURRENT_NET_STATE = NetState.NoWay;
        }

        CoreLog.i("INIT", "CUR_NETSTATE=" + (CURRENT_NET_STATE != null ? CURRENT_NET_STATE.name() : null));
    }
}
